43. Parameter sets

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

Parameter sets are used to limit the possible combination of parameters, or to enforce the use of parameters when 1 or more parameters are selected.

The examples will explain the use and reason of a parameter set.

43.1: Parameter set to enforce the use of a parameter when a other is selected

When you want for example enforce the use of the parameter Password if the parameter User is provided. (and vice versa)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
Function Do-Something
{
  Param
  (
    [Parameter(Mandatory=$true)]
    [String]$SomeThingToDo,
    [Parameter(ParameterSetName="Credentials", mandatory=$false)]
    [String]$Computername = "LocalHost",
    [Parameter(ParameterSetName="Credentials", mandatory=$true)]
    [String]$User,
    [Parameter(ParameterSetName="Credentials", mandatory=$true)]
    [SecureString]$Password
  )

  #Do something
}

# This will not work he will ask for user and password
Do-Something -SomeThingToDo 'get-help about_Functions_Advanced' -ComputerName

# This will not work he will ask for password
Do-Something -SomeThingToDo 'get-help about_Functions_Advanced' - User

43.2: Parameter set to limit the combination of parameters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Function Do-Something
{
  Param
  (
    [Parameter(Mandatory=$true)]
    [String]$SomeThingToDo,
    [Parameter(ParameterSetName="Silently", mandatory=$false)]
    [Switch]$Silently,
    [Parameter(ParameterSetName="Loudly", mandatory=$false)]
    [Switch]$Loudly
  )

  #Do something
}

# This will not work because you can not use the combination Silently and Loudly
Do-Something -SomeThingToDo 'get-help about_Functions_Advanced' - Silently -Loudly